﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.SharePoint;

namespace VH.SharePoint.Api.Entensions
{
    public static class SPFolderExtensions
    {
        public static SPFolder TryGetOrCreateRecurive(this SPFolder rootFolder, string url)
        {
            try
            {
                if (string.IsNullOrEmpty(url)) return rootFolder;
                var web = rootFolder.ParentWeb;
                var retFolder = web.GetFolder(url);
                if (retFolder.Exists)
                    return retFolder;
                url = url.Replace(rootFolder.ServerRelativeUrl, "");
                Uri uri = null;
                if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
                    throw new ArgumentException("The url path is not correct", "url");
                if (uri.IsAbsoluteUri)
                    throw new ArgumentException("The url must be relative.", "url");
                var folder = rootFolder;
                var segments = uri.ToString().Split('/');
                foreach (var segment in segments)
                {
                    var seg = segment.Replace("/", "").ToLowerInvariant();
                    if (string.IsNullOrEmpty(seg)) continue;
                    if (folder.Name.ToLowerInvariant() == seg) continue;
                    try
                    {
                        folder = folder.SubFolders[seg];
                    }
                    catch (ArgumentException)
                    {
                        folder = folder.SubFolders.Add(seg);
                    }
                }
                return folder;

            }
            catch (Exception e)
            {
                throw e;
            }
            return null;
        }
    }
}
